package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catalog2Vo;
import org.redisson.api.RCountDownLatch;
import org.redisson.api.RLock;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {


    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redisson;
    @GetMapping( value = "/")
    public String indexPage(Model model) {

        // 一级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();

        model.addAttribute("categories",categoryEntities);
        return "index";
    }


    // index/json/catalog.json
    @ResponseBody
    @GetMapping("/index/json/catalog.json")
    public Map<String, List<Catalog2Vo>> getCatalogJson(){
        Map<String, List<Catalog2Vo>> catalogJson = categoryService.getCatalogJson();
        return catalogJson;
    }


    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        RLock lock = redisson.getLock("my-lock");

        // 阻塞试等待
        lock.lock(10, TimeUnit.SECONDS);
        try {
            System.out.println("枷锁成功");
            Thread.sleep(3000);
        }catch (Exception e) {

        }
        finally {
            System.out.println("释放锁"+Thread.currentThread().getName());
            lock.unlock();
        }

        return "HELLO";
    }


    /**
     * 闭锁
     */
    @ResponseBody
    @GetMapping("/lockDoor")
    public String lockDoor() throws InterruptedException {

        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.trySetCount(5);
        door.await();
        return "放假了";
    }

    @ResponseBody
    @GetMapping("/gogogo/{id}")
    public String gogogo(@PathVariable Long id) throws InterruptedException {

        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.countDown();
        return id + "班走人了";
    }


    /**
     * 信号量
     * 可做限流
     */

    @GetMapping("/park")
    @ResponseBody
    public String park() {
        RSemaphore park = redisson.getSemaphore("park");
        boolean b = park.tryAcquire();
        return "ok" + b;
    }

    @GetMapping("/go")
    @ResponseBody
    public String go() {
        RSemaphore park = redisson.getSemaphore("park");
        park.release();
        return "ok";
    }



}
